import GeoJSON from 'ol/format/GeoJSON'
import geojson from 'ol/format/geojson'
import VectorLayer from 'ol/layer/Vector'
import { Vector as VectorSource } from 'ol/source'
import { useInjectMap } from './hooks/use-inject-map'
import parseStyle from './utils/style'
import { StyleLike } from 'ol/style/Style'

// 样式构造函数
const defaultStyleCreator = (config) => {
  const { stroke, text, fill, styleText } = config
  return (feature) => {
    const name = feature.get('name')
    let content = null
    if (text) {
      content = text ? { text: name, ...styleText } : { text: name, font: '12px' }
    }
    return parseStyle({
      stroke,
      fill,
      text: content
    })
  }
}

export default defineComponent({
  name: 'MapGeo',
  props: {
    data: Object as PropType<geojson>,
    layerStyle: {
      type: [Object, Function],
      default: () => {
        return {
          file: {
            color: 'rgba(255, 255,255, 0.5)'
          },
          stroke: {
            width: 3,
            color: '#409eff'
          }
        }
      }
    },
    zIndex: Number
  },
  setup(props) {
    const { map } = useInjectMap()
    const geoLayer = shallowRef()

    const addLayer = () => {
      const source = new VectorSource({
        format: new GeoJSON()
      })
      const style =
        typeof props.layerStyle === 'function' ? props.layerStyle : parseStyle(props.layerStyle)

      geoLayer.value = new VectorLayer({
        source,
        style: style as StyleLike,
        zIndex: props.zIndex
      })
      map?.addLayer(geoLayer.value)
      nextTick(() => {
        props.data && draw(props.data)
      })
    }

    const draw = (json: geojson) => {
      const geojson = json
      clear()
      if (!json || !geoLayer.value) return
      const features = new GeoJSON().readFeatures(geojson) || []
      const source = geoLayer.value.getSource()
      source?.addFeatures(features)
      const extent = source.getExtent()
      map?.getView().fit(extent, {
        duration: 2000,
        padding: [20, 20, 20, 20]
      })
    }

    const clear = () => {
      const source = geoLayer.value?.getSource()
      source?.clear()
      // 计算geojson 边界
    }

    addLayer()

    watch(
      () => props.data,
      (newwale) => {
        newwale && draw(newwale)
      },
      { immediate: true }
    )

    onBeforeUnmount(() => {
      map?.removeLayer(geoLayer.value)
      clear()
    })

    return {}
  },
  render() {
    return null
  }
})
